<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<title>Booking</title>
	<style>
		.line {overflow:hidden;}
		.seat {
			margin:2px; float:left;
			width:30px; height:30px;
			background:Red;
			border-radius:3px;
		}
		
		.enable {background:Gray;}
		.enable:hover {background:Black;}
		.disable {background:Red;}
	</style>
	<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
	<script src="/socket.io/socket.io.js"></script>
	<script>
		var socket = io.connect();
		
		// event handlers
		socket.on('reserve', function(data) {
			var $target = $('div[data-x = ' + data.x + '][data-y = ' + data.y + ']');
			$target.removeClass('enable');
			$target.addClass('disable');
			$target.off('click');
		});
	</script>
	
	<script>
		$(document).ready(function() {
			var onClickSeat = function() {
				var x = $(this).attr('data-x');
				var y = $(this).attr('data-y');
				
				if (confirm('좌석을 예약하시겠습니까?')) {
					$(this).off('click');
					socket.emit('reserve', {
						x: x,
						y: y
					});
				}
				else {
					alert('취소되었습니다.');
				}
			};
			
			// get seats information
			$.getJSON('/seats', {dummy: new Date().getTime()}, function(data) {
				// create seats
				$.each(data, function(indexY, line) {
					var $line = $('<div></div>').addClass('line');
					
					$.each(line, function(indexX, seat) {
						var $output = $('<div></div>', {
							'class': 'seat',
							'data-x': indexX,
							'data-y': indexY
						}).appendTo($line);
						
						if (seat == 1) {
							// if seat is available, add enable class and click listener
							$output.addClass('enable').on('click', onClickSeat);
						}
						else if (seat == 2) {
							// if seat is not available, add disable class
							$output.addClass('disable');
						}
					});
					
					$line.appendTo('body');
				});
			});
		});
	</script>
</head>
<body>

</body>
</html>